/**
 * create by ck on 2016/3/18.
 */
var teacherId;
var schoolId;
var schoolList;
var techList;
var techParams;
var schParams;
var startDom;
var endDom;
var schStartTime;
var schEndTime;
var searchSch;
var schArea;
var schCity;
var typeDom;
var schState;
$.fn.pagination.defaults.displayMsg = '';
$(document).ready(function(){
    var DataGrid2 = new DataGridEvent();
    schoolList = $('#SchoolList');
    techList   = $('#TeacherList');
    var timer;
    startDom    = $('#List_Search_StartTime');
    endDom      = $('#List_Search_EndTime');
    searchSch   = $('#bt_SchoolList_Search');
    typeDom     = $('#select_type');
    schStartTime = '';
    schEndTime   = '';
    schArea      = '';
    schCity      = '';
    $('.xh-datagrid-toolbar').parseToolbar();

    // startDom.datebox('setValue', GetDateStr(-7));
    // endDom.datebox('setValue', GetDateStr(0));

    schoolList.initDataGrid('getDgData');
    schoolList.datagrid({
        url:baseUrl + 'School/getSchForTch',
        columns:[[
            {field:'iSchoolId'      ,title:'id'      ,align:"center"   ,halign:"center",hidden:true},
            {field:'schoolInfo'     ,title:'#'       ,align:"center"   ,halign:"center",width:'30px',sortable:true},
            {field:'schoolCheck'     ,title:'#2'       ,align:"center"   ,halign:"center",width:'50px'},
            {field:'sSchoolName'    ,title:'学校名称' ,align:"left"     ,halign:"center",width:'160px'},
            {field:'iTchNum'       ,title:'教师'    ,align:"right"     ,halign:"center",width:'40px'},
        ]]
    });
    //学校列表加载后刷新教师列表
    DataGrid.onLoadSuccess = function(data){
        if(data['rows'].length <= 0) return false;
        var startTime = xhExtra.getValue($('#List_Search_StartTime'));
        var endTime   = xhExtra.getValue($('#List_Search_EndTime'));
        var type      = xhExtra.getValue($('#select_type'));
        var log       = xhExtra.getValue($('#select_log'));
        var subject   = xhExtra.getValue($('#select_subject'));
        var history   = xhExtra.getValue($('#select_history'));
        var trackType = xhExtra.getValue($('#select_trackType'));
        var grade     = xhExtra.getValue($('#select_grade'));
        var important     = xhExtra.getValue($('#select_important'));
        var excellent     = xhExtra.getValue($('#select_excellent'));
        var proficiency     = xhExtra.getValue($('#select_proficiency'));
        var tchType     = xhExtra.getValue($('#select_tchType'));
        var statsInLog     = xhExtra.getValue($('#select_tchLogIn'));
        // schoolId = data['rows'][0].iSchoolId;
        techParams = {"iUserType": 4,'iSchoolId':null,key:null,startTime:startTime,endTime:endTime,type:type,log:log,subject:subject,schArea:schArea,schCity:schCity,history:history,trackType:trackType,grade:grade
            ,important:important,excellent:excellent,proficiency:proficiency,tchType:tchType,statsInLog:statsInLog};
        techList.initDataGrid(baseUrl + 'School/getTchData', {"queryParams": techParams}, DataGrid2)
            .setSelectThenEnable(['bt_list_OpenClass', 'bt_list_ViewClass','bt_list_setGrade'], [], 'eu', DataGrid2)
            .datagrid('getPanel').panel('setTitle', '教师列表（全部）');
        $('#bt_list_OpenClass').setButtonDisable('eu');
        // afterParseToolbar();


        // bindMouseOverFunc();

    };

    //点击学校列表在学生列表显示相应学生
    DataGrid.onSelect = function(rowIndex, rowData){
        schoolId = rowData.iSchoolId;
        techParams.iSchoolId = schoolId;
        techList.addDataGridParams(techParams)
            .datagrid('getPanel').panel('setTitle', '教师列表（' + rowData.sSchoolName + '）');
        // afterParseToolbar();
    };
    schoolList.datagrid({
        onBeforeSelect: function(rowIndex, rowData){  //去除点击事件
            var flag=false;
            if(schoolId!=undefined&&schoolId==rowData['iSchoolId']){
                schoolId=null;
                techParams.iSchoolId = schoolId;
                techList.addDataGridParams(techParams)
                    .datagrid('getPanel').panel('setTitle', '教师列表（全部）');
                flag=true;
            }
            if(flag){
                schoolList.datagrid('unselectAll');
                return false;
            }

        }
    });

    //点击开课后跳转到相应页面
    //$('#bt_list_OpenClass').click(function(){
    //    if($(this).checkButtonDisabled()) return false;
    //    teacherId = techList.getDataGridSelectedFields('iUserId');
    //    var src = baseUrl + 'School/schoolChooseApp';
    //    window.top.createModal(
    //        "<iframe frameborder='0' style='width: 100%;height: 600px;' src='" + src + "'></iframe>",
    //        '选择应用', '', 'lg'
    //    );
    //});
    $('#bt_list_ViewClass').click(function(){
        if($(this).checkButtonDisabled()) return false;
        teacherId = techList.getDataGridSelectedFields('iUserId');
        var src = baseUrl + 'Class/teacherClassList?iTeacherId=' + teacherId + '&iSchoolId=' + schoolId;
        window.top.xhTop.showModal({
            title: '查看教师开班信息',
            content: "<iframe frameborder='0' style='width: 100%;height: 600px;' src='" + src + "'></iframe>",
            size: 'lg'
        });
    });
    DataGrid2.onDblClickRow=function (rowIndex, rowData) {
        var iUserId=rowData['iUserId'];
        window.top.xhTop.createNewTab('教师信息',baseUrl+'frontend/Tch/TchTab/'+iUserId,true);
    }


    DataGrid2.rowStyler = function(rowIndex, rowData){

        if(rowData['extra'] != null){
            if(rowData['extra']['flag']==true){
                $('tr[datagrid-row-index="'+ rowIndex +'"]').find('td[field="sUserName"]').css('color', '#2baab1');
            }
        }
    };
    $(function () {

        techList.datagrid({
            view: detailview,
            detailFormatter:function(index,row){

                var str='<div class="ddv" style="padding:5px 0;overflow: auto;position: relative"  ><table >';
                if(row['extra'] != null){
                    str+='<tr><td style="width: 70px">跟踪类型:</td><td><p>'+row['extra']['iTrackType']+'</p></td></tr>';
                    str+='<tr><td style="width: 70px">跟进时间:</td><td><p>'+row['extra']["tTrackTime"]+' &nbsp;<font style="color: grey;">(创建时间:&nbsp;'+row['extra']["tCreateDate"]+')</font></p></td></tr>';
                    str+='<tr><td style="width: 70px">沟通目的:</td><td><p>'+row['extra']['mPurpose']+'</p></td></tr>';
                    str+='<tr><td style="width: 70px">沟通内容:</td><td><p>'+row['extra']['mContent']+'</p></td></tr>';
                    str+='<tr><td style="width: 70px">沟通结果:</td><td><p>'+row['extra']['mResult']+'</p></td></tr>';
                    str+='<tr><td style="width: 70px">原因分析:</td><td><p>'+row['extra']['mAppUse']+'</p></td></tr>';
                    str+='<tr><td style="width: 70px">审核理由:</td><td><p>'+row['extra']['mCheck']+'</p></td></tr>';
                    if(row['extra']['iState'] == 1){
                        str += '<div style="position:absolute;height: 100px;width: 100px;z-index: 0;bottom: 5px;right: 10px;"><img src="http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest/f3f03dfae59741e1b1529c6f10bc7e37.png" style="width: 100%;height: 100%;opacity: 0.5;"></div>';
                    }else if(row['extra']['iState'] == 2) {
                        str += '<div style="position:absolute;height: 100px;width: 100px;z-index: 0;bottom: 5px;right: 10px;"><img src="http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest/ccb87932a83a440ca717eeb00ddd8ef4.png" style="width: 100%;height: 100%;opacity: 0.5;"></div>';
                    }else if(row['extra']['iState'] == 3){
                        str +=  '<div style="position:absolute;height: 100px;width: 100px;z-index: 0;bottom: 5px;right: 10px;"><img src="http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest/b392e44af9674f0cb56fb279a5b79e14.png" style="width: 100%;height: 100%;opacity: 0.5;"></div>';
                    }
                }else {
                    str+='<p>没有跟进记录</p>';
                }
                str+='</table>';
                str+='</div>';
                return str;
            },
            onExpandRow: function(index,row){
                var ddv = $(this).datagrid('getRowDetail',index).find('div.ddv');
                ddv.panel({
                    // height:80,
                    width:690,
                    border:false,
                    cache:false,
                    onLoad:function(){
                        techList.datagrid('fixDetailRowHeight',index);
                        techList.datagrid('fixDetailRowWidth',index);
                    }
                });
                techList.datagrid('fixDetailRowHeight',index);
            }
            
        });
        DataGrid2.onLoadSuccess=function (data) {
            var row = techList.datagrid("getRows");
            for (var r = 0; r < row.length; r++)
            {
                if(row[r]['extra']!=null){
                    techList.datagrid("expandRow",r);
                }
            }
        }
    });

    $('#bt_SchoolList_Time').click(function () {
       window.top.xhTop.showModal({
           title: '选择更新时间区间',
           content: '<iframe src="'+baseUrl+'Tch/time?schStartTime='+schStartTime+'&schEndTime='+schEndTime+'&schCity='+schCity+'&schArea='+schArea+'&key='+escape(xhExtra.getValue($('#SchoolList_Search')))+'&status='+xhExtra.getValue($('#list_search_status'))+'"  style="width: 100%;;border-style: none;padding: 0px;height:220px"  scrolling="yes"   ></iframe>',
           size: 'md',
           button:'提交',
       });
    });

    $('#bt_SchoolList_Search').click(function () {
        schParams = {
            key:xhExtra.getValue($('#SchoolList_Search')),
            startTime:schStartTime,
            endTime:schEndTime,
            schArea:schArea,
            schCity:schCity,
            schState:xhExtra.getValue($('#list_search_status')),
        }
        schoolList.addDataGridParams(schParams);
    });


    $('#bt_TeacherList_Search').click(function () {
        techParams.key       = xhExtra.getValue($('#TeacherList_Search'));
        techParams.startTime = xhExtra.getValue($('#List_Search_StartTime'));
        techParams.endTime   = xhExtra.getValue($('#List_Search_EndTime'));
        techParams.type      = xhExtra.getValue($('#select_type'));
        techParams.log       = xhExtra.getValue($('#select_log'));
        techParams.subject   = xhExtra.getValue($('#select_subject'));
        techParams.trackType = xhExtra.getValue($('#select_trackType'));
        techParams.schCity   = schCity;
        techParams.schArea   = schArea;
        techParams.history   = xhExtra.getValue($('#select_history'));
        techParams.grade     = xhExtra.getValue($('#select_grade'));
        techParams.important     = xhExtra.getValue($('#select_important'));
        techParams.excellent     = xhExtra.getValue($('#select_excellent'));
        techParams.proficiency     = xhExtra.getValue($('#select_proficiency'));
        techParams.tchType     = xhExtra.getValue($('#select_tchType'));
        techParams.statsInLog     = xhExtra.getValue($('#select_tchLogIn'));
        var str = schoolList.getDataGridSelectedField('sSchoolName');
        if(str==''){
            str = '全部';
        }
        techList.addDataGridParams(techParams)
            .datagrid('getPanel').panel('setTitle', '教师列表（' +str+'）');
    });

    $('#bt_list_setGrade').click(function () {
        if (xhExtra.buttonDisabled($(this))) {
            return false;
        }
        var tchIds = techList.getDataGridSelectedFields('iUserId', true);
        var html = '<select id="currentGrade" class="swal2-select" style="width: 100%;">';
            html += '<option value="" style="display: none" selected>请选择</option>' ;
            if (gradeEnum) {
                $.each(gradeEnum,function (id,text) {
                    html += '<option value="'+id+'">'+text+'</option>';
                })
            }
            html += '</select>';

        window.top.swal({
            title: '设置当前年级',
            confirmButtonText: '确定',
            showCancelButton: true,
            cancelButtonText: '取消',
            showLoaderOnConfirm: true,
            allowOutsideClick: false,
            html: html,
            preConfirm: function() {
                return new Promise(function (resolve, reject) {
                    var currentGrade = $('#currentGrade', window.top.document).val();
                    if (!currentGrade){
                        reject('年级未选择！');
                    } else {
                        resolve(currentGrade);
                    }
                })
            }
        }).then(function (currentGrade) {
            xhExtra.ajaxRequest('school/setCurGrade',{tchIds:tchIds,currentGrade:currentGrade},{},function (res) {
                window.top.xhTop.showSuccess(res.msg);
                techList.dataGridReload();
            })
        },function (dismiss) {
            return false;
        });
    })
    

});
function bindMouseOverFunc() {
    $('#schoolListTd .datagrid-body [field=sSchoolName]').on({
        "mouseenter":function(){
            var schoolId = $(this).parent().find('[field=iSchoolId] div').text();

            clearTimeout(timer);
            timer=setTimeout(function(){
                //这里触发hover事件
                console.log(schoolId);
                $.ajax({
                    url:baseUrl+'Tch/',
                    dataType:'json',
                    data:{schoolId:schoolId},
                    type:'post',
                    success : function (data) {
                        console.log(data);
                    },
                    error : function (data) {
                        console.log(data);
                    }
                })

            },1000);
        }
    });
}

//选择应用，供子页面调用
//function chooseAppStore(iAppCode){
//    window.top.xhTop.createNewTab('应用开课', baseUrl + 'Class/openClass?iTeacherId=' + teacherId + '&iAppCode=' + iAppCode + '&iSchoolId=' + schoolId);
//    //window.location.href = "../Class/openClass?iTeacherId="+teacherId+"&iAppCode="+iAppCode+"&iSchoolId="+schoolId;
//}
function afterParseToolbar() {
    // $('#bt_SchoolList_Search, #bt_TeacherList_Search').unbind('click');
    // $('#bt_SchoolList_Search').unbind('click');
    // $.overtFun.vagueSearch(schoolList, null, $('#SchoolList_Search'), $('#bt_SchoolList_Search'));
    // $.overtFun.vagueSearch(techList, techParams, $('#TeacherList_Search'), $('#bt_TeacherList_Search'));
}
function GetDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth()+1;//获取当前月份的日期
    var d = dd.getDate();
    return y+"-"+m+"-"+d;
}